var $j = jQuery.noConflict();

$j(function()
{
	if (typeof ace !== 'undefined')
	{
		$j('form:has(.pim-editor-text)').each(function()
		{
			var form, editors, editorContainers;
			
			form = $j(this);
			editors = form.find('.pim-editor-text');
			editorContainers = [];
			
			// Hide the <textarea>'s and show an Ace editor instead.
			editors.hide().each(function()
			{
				var textarea, editorContainer, editor, session, HTMLMode;
				
				textarea = $j(this);
				
				editorContainer = $j('<div class="pim-ace-editor"></div>').insertBefore(this)[0];
				editorContainers.push(editorContainer);
				
				editor = ace.edit(editorContainer);
				editor.setTheme('ace/theme/twilight');
				
				session = editor.getSession();
				HTMLMode = require('ace/mode/html').Mode;
				session.setMode(new HTMLMode());
				session.setUseSoftTabs(false);
				session.setUseWrapMode(true);
				session.setWrapLimitRange(120, 120);
				session.setTabSize(4);
				session.setValue(textarea.val());
			});
			
			// On submit, read the ace editors contents and insert it in the <textarea>.
			form.submit(function()
			{
				for (var i = 0, length = aceEditors.length; i < length; i++)
				{
					editors.eq(i).val(aceEditors[i].env.document.getValue());
				}
			});
		});
	}
});

/*
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/twilight");
    
    var JavaScriptMode = require("ace/mode/javascript").Mode;
    editor.getSession().setMode(new JavaScriptMode());
*/